var express = require('express')
var router = express.Router()
const { getALL, getById, exec } = require('../db')

/* 获取事件 */
router.post('/get', async (req, res) => {
  const { page = 1, size = 5 } = req.body
  // console.log(page)
  // console.log(size)
  var offset = (page - 1) * size
  let sql = `select event_id,event_time,username,event_addr,event_describe,event_status from gg_event INNER JOIN gg_user ON gg_event.user_id = gg_user.user_id limit ${offset},${size}`
  let sql1 = 'select count(*) as total from gg_event'
  const data = await getALL(sql)
  var { total } = await getById(sql1)
  var totals = total
  res.send({
    code: 101,
    msg: '获取事件成功',
    data,
    totals,
  })
})
/* 上传事件 */
router.post('/', async (req, res) => {
  const { event_type, event_addr, event_describe, user_id } = req.body
  let sql = `insert into gg_event(user_id,event_type, event_addr,event_time,event_describe,event_status) values('${user_id}','${event_type}','${event_addr}',NOW(),'${event_describe}','0')`
  console.log(sql)
  const data = await exec(sql)
  res.send({
    code: 202,
    msg: '添加事件成功',
    data,
  })
})
/* 更新事件状态 */
router.put('/', async (req, res) => {
  const { id, status } = req.body
  let sql = `UPDATE gg_event SET event_status = '${status}' WHERE event_id = '${id}'`
  const data = await exec(sql)
  res.send({
    code: 303,
    msg: '事件状态更新成功',
    data,
  })
})
router.delete('/:id', async (req, res) => {
  const { id } = req.params
  let sql = `delete from gg_event where event_id = '${id}'`
  const data = await exec(sql)
  res.send({
    code: 303,
    msg: '事件删除成功',
  })
})
module.exports = router
